<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/6/16
 * Time: 21:00
 */
namespace Pay\Controller;

use Common\Common\Api\Order;
use Common\Common\Api\Ordermember;
use Common\Common\Api\Redis\Channel;
use Common\Common\Api\Redis\Product;

/**
 * Class ManyiController
 * @package Pay\Controller
 * 亿易2
 */
class Yiyi2Controller extends PayController{
    protected $config;
    protected $class;
    public function __construct(){
        parent::__construct();
        $classes = explode("\\",__CLASS__);
        $class = end($classes);
        $this->class = substr($class, 0, stripos($class, "Controller"));
    }

    public function pay($array){
        $this->config = Channel::getInstance()->getById($array['channel']);

        if(!$this->config){
            $this->showmessage('通道错误!',['code'=>C("THIRDCODES.".$this->class)]);
        }

        $product = Product::getInstance()->getById(I("request.pay_bankcode",0,"intval"));

        if(!$product){
            $this->showmessage('未找到支付产品!',['code'=>C("THIRDCODES.".$this->class)]);
        }

        $parameter = array(
            'code' => $this->config['code'], // 通道名称
            'title' => $this->config['title'],
            'exchange' => 1, // 金额比例
            'gateway' => $this->config['gateway'],
            'orderid' => createOrderId(),
            'out_trade_id' => I("request.pay_orderid"),
            'body' => 'pay',
            'channel'=>$array
        );

        $isMobile = isMobile();

        $return = $this->orderadd( $parameter );

        $data = array();
        $data['merchantId'] = $this->config['mch_id'];
        $data['timestamp'] = substr(str_replace(".","",microtime(true)),0,13);
        $data['tradeNo'] = $return['orderid'];
        $data['notifyUrl'] = $return['notifyurl'];
        $data['amount'] = $return['amount'];
        $data['payWay'] = 2;
        $data['status'] = '1000';
        $data['signature'] = $this->getSign($data);

        $res = curl($this->config['gateway'], httpstr($data));

        $res = json_decode($res, true);

        $code = $res['data']['codeUrl'];

        if(!$code){
            if($res['msg']){
                $this->showmessage($res['msg'],['code'=>C("THIRDCODES.".$this->class)]);
            }

            $this->showmessage('未获取到支付链接!',['code'=>C("THIRDCODES.".$this->class)]);
        }

        $paytype = transArr( C("PAYTYPES"), "id");

        $this->assign("wap_url", $code);
        //$this->assign("code_url", $res['data']['payurl']);
        $this->assign("title", $paytype[$this->config['paytype']]);
        $this->assign("return", $return);
        $this->assign("imgurl", C("website.DOMAIN")."/Pay_Qrcode_getCode?type=2&data=" . base64_encode($code));

        switch($this->config['paytype']){
            //支付宝扫码
            case 3:
                //支付宝H5
            case 4:
                if(isMobile()){
                    header("Location:{$code}");
                }else{
                    $this->display("WeiXin/alipay");
                }
                break;
            default:
                $this->display("WeiXin/Pay");
        }
    }

    private function getSign($data){
        ksort($data);

        $str = "";
        foreach($data as $k=>$v){
            if($k === 'signature' || $v === ''){
                continue;
            }

            $str .= "{$k}={$v}&";
        }

        $str = substr($str,0,-1);

        return hash_hmac("sha1",$str,$this->config['signkey']);
    }

    //通知
    public function notifyurl(){
        file_put_contents("a.txt", var_export($_POST,true)."\r\n\r\n");
        file_put_contents("a.txt", var_export($_GET,true)."\r\n\r\n", FILE_APPEND);
        file_put_contents("a.txt", file_get_contents('php://input')."\r\n\r\n", FILE_APPEND);
        file_put_contents("a.txt", date("Y-m-d H:i:s",time())."\r\n\r\n", FILE_APPEND);


        $p = $origin = file_get_contents('php://input');

        //$p = 'body=%7B%22date%22%3A%221545970542000%22%2C%22totalAmount%22%3A%2240.00%22%2C%22tradeNo%22%3A%222018122812152260450%22%2C%22merchantId%22%3A%22100000000000013%22%2C%22signature%22%3A%22ed893e8df66a37b6a17e6dd85662f3e4697850a5%22%2C%22tradeState%22%3A%221%22%7D';

        $p = urldecode($p);
        $p = str_replace("body=",'',$p);
        $p = json_decode($p, true);

        /*
         * Array
        (
            [date] => 1545968167000
            [totalAmount] => 15.00
            [tradeNo] => 2018122811354440979
            [merchantId] => 100000000000013
            [signature] => c88fc967eba46010b468503de65a6be22645e001
            [tradeState] => 1
        )
         */

        if(!$p || empty($p)){
            exit("wrong");
        }

        //获取订单信息
        $orderid = $p['tradeNo'];
        $find = M("Order")->where(array("pay_orderid"=>$orderid))->find();
        if(!$find){
            echo 'order_not_found'; exit;
        }

        //保存回调数据
        M("Order")->where(array("pay_orderid"=>$orderid))->save(array(
            "server_return"=> $origin,
            //"pay_orderid_rd"=>$p['sysnumber']
        ));

        //获取渠道信息
        $this->config = M("Channel")->where(array('code'=>$this->class))->find();

        $sign = $p['signature'];
        $sign2 = $this->getSign($p);

        if($sign !== $sign2){
            exit("sign_wrong");
        }

        if($p['tradeState'] != '1'){
            exit("pay_fail");
        }

        $this->async($find['pay_orderid'],'success');
    }

    public function callBackUrl(){

        echo '处理成功'; exit;
    }
}